package com.quectel.core.module.entranceguard.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.quectel.constant.global.SqlConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.device.dto.DeviceDto;
import com.quectel.core.module.device.service.DeviceService;
import com.quectel.core.module.entranceguard.dao.EntranceGuardPersonDao;
import com.quectel.core.module.entranceguard.dto.EntranceGuardPersonDto;
import com.quectel.core.module.entranceguard.dto.VisitorDto;
import com.quectel.core.module.entranceguard.entity.EntranceGuardPersonEntity;
import com.quectel.core.module.entranceguard.service.EntranceGuardPersonService;
import com.quectel.core.module.entranceguard.service.VisitorService;
import com.quectel.core.module.household.dto.HouseholdDto;
import com.quectel.core.module.household.service.HouseholdService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * @author caolu
 * @email louis.cao@quectel.com
 * @date 2021-11-17 13:42:49
 */
@DubboService
public class EntranceGuardPersonServiceImpl implements EntranceGuardPersonService {

    private static final Logger LOGGER = LoggerFactory.getLogger(EntranceGuardPersonServiceImpl.class);

    private static final String ENTRANCE_GUARD_PERSON_CACHE_BY_ID = RedisCacheConstants.PROJECT_NAME + "ENTRANCE_GUARD_PERSON_CACHE_BY_ID:";
    private static final String AUTH_CACHE_BY_ID = RedisCacheConstants.PROJECT_NAME + "AUTH_CACHE_BY_ID:";

    @Autowired
    private EntranceGuardPersonDao entranceGuardPersonDao;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private HouseholdService householdService;
    @Autowired
    private VisitorService visitorService;


    @Override
    public EntranceGuardPersonDto queryAuthBy(Long deviceId, Byte personType, Long personId) {
        EntranceGuardPersonEntity entranceGuardPersonEntity = entranceGuardPersonDao.selectOne(
                new LambdaQueryWrapper<EntranceGuardPersonEntity>()
                        .eq(EntranceGuardPersonEntity::getDeviceId, deviceId)
                        .eq(EntranceGuardPersonEntity::getPersonType, personType)
                        .eq(EntranceGuardPersonEntity::getPersonId, personId)
                        .last(SqlConstants.MYSQL_LIMIT_ONE)
        );

        return CopyUtils.copyObj(entranceGuardPersonEntity, EntranceGuardPersonDto.class);
    }

    @Override
    public EntranceGuardPersonDto queryCacheAuthBy(Long deviceId, String identityAtDevice) {
        return CacheKit.cacheToRedis(
                () -> queryCacheAuthBy(deviceId, identityAtDevice),
                AUTH_CACHE_BY_ID + deviceId + ":" + identityAtDevice,

                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public EntranceGuardPersonDto queryAuthBy(Long deviceId, String identityAtDevice) {
        EntranceGuardPersonEntity entranceGuardPersonEntity = entranceGuardPersonDao.selectOne(
                new LambdaQueryWrapper<EntranceGuardPersonEntity>()
                        .eq(EntranceGuardPersonEntity::getDeviceId, deviceId)
                        .eq(EntranceGuardPersonEntity::getIdentityAtDevice, identityAtDevice)
                        .last(SqlConstants.MYSQL_LIMIT_ONE)
        );

        return CopyUtils.copyObj(entranceGuardPersonEntity, EntranceGuardPersonDto.class);
    }

    @Override
    public List<EntranceGuardPersonDto> queryAuthByPersonId(Byte personType, Long personId) {
        List<EntranceGuardPersonEntity> entranceGuardPersonEntities = entranceGuardPersonDao.selectList(new LambdaQueryWrapper<EntranceGuardPersonEntity>()
                .eq(EntranceGuardPersonEntity::getPersonType, personType)
                .eq(EntranceGuardPersonEntity::getPersonId, personId));
        List<EntranceGuardPersonDto> entranceGuardPersonDtos = CopyUtils.copyList(entranceGuardPersonEntities, EntranceGuardPersonDto.class);
        entranceGuardPersonDtos.forEach(this::paddingField);
        return entranceGuardPersonDtos;
    }

    @Override
    public EntranceGuardPersonDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                ENTRANCE_GUARD_PERSON_CACHE_BY_ID + id,

                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public EntranceGuardPersonDto selectById(Long id) {
        EntranceGuardPersonEntity entity = entranceGuardPersonDao.selectById(id);
        return paddingField(CopyUtils.copyObj(entity, EntranceGuardPersonDto.class));
    }

    @Override
    public List<EntranceGuardPersonDto> queryList(Map<String, Object> params) {
        List<EntranceGuardPersonEntity> list = entranceGuardPersonDao.queryList(params);
        List<EntranceGuardPersonDto> result = CopyUtils.copyList(list, EntranceGuardPersonDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    private EntranceGuardPersonDto paddingField(EntranceGuardPersonDto dto) {
        if (dto != null) {
            DeviceDto deviceDto = deviceService.selectCacheById(dto.getDeviceId());
            dto.setDevice(deviceDto);

            if (SystemConstants.PlatformPersonType.HOUSEHOLD.getType().equals(dto.getPersonType())) {
                HouseholdDto householdDto = householdService.selectCacheById(dto.getPersonId());
                if (householdDto != null) {
                    dto.setPersonName(householdDto.getName());
                }
            } else if (SystemConstants.PlatformPersonType.VISITOR.getType().equals(dto.getPersonType())) {
                VisitorDto visitorDto = visitorService.selectCacheById(dto.getPersonId());
                if (visitorDto != null) {
                    dto.setPersonName(visitorDto.getName());
                }
            }
        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params) {
        return entranceGuardPersonDao.queryTotal(params);
    }

    @Override
    public Long save(EntranceGuardPersonDto dto) {
        EntranceGuardPersonEntity entity = CopyUtils.copyObj(dto, EntranceGuardPersonEntity.class);
        entity.setId(Snowflake.nextId());
        entranceGuardPersonDao.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateById(EntranceGuardPersonDto dto) {
        EntranceGuardPersonEntity entity = CopyUtils.copyObj(dto, EntranceGuardPersonEntity.class);
        entranceGuardPersonDao.updateById(entity);
        CacheKit.invalidRedisCache(ENTRANCE_GUARD_PERSON_CACHE_BY_ID + dto.getId());
    }

    @Override
    public void updateAllColumnById(EntranceGuardPersonDto dto) {
        EntranceGuardPersonEntity entity = CopyUtils.copyObj(dto, EntranceGuardPersonEntity.class);


        MyBatisPlusUtils.updateAllColumnById(entity, entranceGuardPersonDao);

        CacheKit.invalidRedisCache(ENTRANCE_GUARD_PERSON_CACHE_BY_ID + dto.getId());
    }

    @Override
    public void deleteById(Long id) {
        entranceGuardPersonDao.deleteById(id);

        CacheKit.invalidRedisCache(ENTRANCE_GUARD_PERSON_CACHE_BY_ID + id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids) {
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
